import React from 'react'
import PropTypes from 'prop-types'
import { Button, message, Space, Modal } from 'antd'
import moment from 'moment'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { addWindow } from '@redux/actions'
import { ApproveBlock, Header, TextLine, TextCell, Split, TitleLine } from '@components/ApprovePre/Approve'
import style from './AcceptCase.module.less'
import { caseStatusList } from '@js/config'
import SameModal from './AcceptCase/SameModal'
const { confirm } = Modal
class AcceptCase extends Component {
  state = {
    ready: false,
    creatingDoc: false,
    loading: false,
    caseList: [],
    sameLoading: false
  }

  // 设置案件状态
  setCaseStatus (status, forcepassage) {
    const { realname, id } = this.props.userInfo
    const hide = message.loading('加载中', 120)
    const data = {
      status,
      accepter: realname,
      accepterid: id
    }
    if (forcepassage) {
      data.forcepassage = 1
    }
    this.$put(`/api/xapc/case/${this.props.caseDetail.id}`, data).then(res => {
      hide()
      if (res.status === 1) {
        this.props.refreshCaseData && this.props.refreshCaseData()
        this.createAcceptDoc()
      } else if (res.status === 2) {
        this.requestAgainConfirm(res.message, () => this.setCaseStatus(status, true))
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  //  强制重新请求提示
  requestAgainConfirm (content, onOk) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content,
      onOk,
      okText: '强制提交'
    })
  }

  // 格式化日期
  formatDate (d) {
    return moment(d * 1000).format('YYYY-MM-DD HH:mm')
  }

  // 生成收案文书
  createAcceptDoc () {
    if (this.state.loading) {
      return false
    }
    const id = this.props.caseDetail.id
    this.setState({
      loading: true
    })
    this.$createDoc(this.props.caseDetail.id, ['立案事宜通知书'])
      .then(() => {
        setTimeout(() => {
          this.setState({
            loading: false
          })
        }, 200)
        this.$getFileList(id)
      }).catch(() => {
        setTimeout(() => {
          this.setState({
            loading: false
          })
        }, 200)
      })
  }

  // 重新生成收案文书
  createAcceptDocAgain (id) {
    const hide = message.loading('重新生成文书中', 120)
    this.$post('/api/vendor/case/regenerate_file', {
      id,
      reload: 1
    }).then(res => {
      hide()
      if (res.status === 1) {
        this.$getFileList(this.props.caseDetail.id)
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  againConfirm (id) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要重新生成文书吗？',
      onOk: () => {
        this.createAcceptDocAgain(id)
      }
    })
  }

  // 判断文书是否生成成功，如果存在则返回文书id
  isFileCreateSuccess () {
    if (!this.state._fileListLoaded) {
      return true
    }
    const list = this.state._fileList || []
    let id = false
    for (let i = 0; i < list.length; i++) {
      if ((list[i].title || '').indexOf('立案事宜通知书') !== -1) {
        id = list[i].id
        break
      }
    }
    return id
  }

  // 获取类案数据
  getSameCaseList () {
    this.setState({ sameLoading: true })
    // 获取类案数据
    this.$get('/api/xapc/case/caseLike2and', {
      caseid: this.props.caseDetail.id,
      current: 1,
      page_size: 1000
    }).then(res => {
      this.setState({ sameLoading: false })
      if (res.status === 1) {
        const list = res.data.list
        this.setState({ caseList: list })
      } else {
        message.warning(res.message)
      }
    }).catch(() => this.setState({ sameLoading: false }))
  }

  // 查看案件详情
  openDetail (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id, editable: false } })
  }

  componentDidUpdate (prev) {
    if (prev.caseDetail !== this.props.caseDetail) {
      this.getSameCaseList()
      this.$getFileList(this.props.caseDetail.id)
    }
  }

  componentDidMount () {
    if (this.props.caseDetail.id) {
      this.getSameCaseList()
      this.$getFileList(this.props.caseDetail.id)
    }
  }

  // 渲染已提交的相关操作，“生成文书”和“不与受理”按钮
  renderSubmitedOperate () {
    const { _fileCreating } = this.state
    const { editable } = this.props
    if (!editable) {
      return false
    }
    return (
      <>
        <ApproveBlock>
          <Header title='收案'>
            <Button disabled={!this.props.editable || this.state.loading} type='primary' loading={_fileCreating} onClick={() => this.setCaseStatus('收案')}>生成文书</Button>
          </Header>
        </ApproveBlock>
        <SameModal list={this.state.caseList} loading={this.state.sameLoading} toDetail={d => this.openDetail(d)} />
      </>
    )
  }

  // 渲染立案模块
  renderAcceptBlock () {
    const d = this.props.caseDetail || {}
    const docId = this.isFileCreateSuccess()
    return (
      <ApproveBlock>
        <Header title='收案' />
        <TextLine>
          <TextCell>立案员：{d.accepter || ''}</TextCell>
          <Split />
          <TextCell>立案时间：{d.docket_datetime ? this.formatDate(d.docket_datetime) : ''}</TextCell>
        </TextLine>
        <TitleLine title='文书打印' />
        <TextLine>
          <Space size='middle'>
            {docId ? <span className={style.file} onClick={() => this.$readerFileByName('立案事宜通知书', d.id)}>立案事宜通知书.pdf</span> : null}
            {docId ? (
              <Button disabled={this.state.loading} type='primary' onClick={() => this.againConfirm(docId)}>重新生成</Button>
            ) : (
              <Button disabled={this.state.loading} type='primary' onClick={() => this.createAcceptDoc()}>生成文书</Button>
            )}
          </Space>
        </TextLine>
      </ApproveBlock>
    )
  }

  render () {
    const { status } = this.props.caseDetail || {}
    if (caseStatusList.indexOf(status) === -1) {
      return this.renderSubmitedOperate()
    }
    return this.renderAcceptBlock()
  }
}

AcceptCase.propTypes = {
  caseDetail: PropTypes.object,
  // active: PropTypes.bool,
  refreshCaseData: PropTypes.func,
  editable: PropTypes.bool
}
AcceptCase.defaultProps = {
  caseDetail: {},
  // active: false,
  refreshCaseData: () => {},
  editable: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(AcceptCase)
